package action;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Util;
import dm.CriteriaDM;

import gate.ActionHandler;

public class ActionCriteria implements ActionHandler{

	@Override
	public void handleAction(HttpServletRequest request, HttpServletResponse response) {

		try{
			String action = request.getParameter("action");
			
			
			String url = request.getParameter("url");
			CriteriaDM dm = new CriteriaDM();
			
			try{
				if(action.equals("addCriteria")){
					
					String id = request.getParameter("categoryId");
					String name = request.getParameter("criteriaName");
					
					dm.insertCriteria(id, name);
					
				}else if (action.equals("updateCriteria")) {
					
					int id = Util.toInt(request.getParameter("criteriaId"));
					String name = request.getParameter("criteriaName");
					
					dm.updateCriteria(id, name);
					
				}else if (action.equals("delCriteria")) {
					
					int id = Util.toInt(request.getParameter("criteriaId"));
					
					dm.delCriteria(id);
					
				}if(action.equals("addSubCriteria")){
					
					int id = Util.toInt(request.getParameter("criteriaId"));
					String name = request.getParameter("criteriaName");
					
					dm.insertSubCriteria(id, name);
					
				}else if (action.equals("updateSubCriteria")) {
					
					int id = Util.toInt(request.getParameter("subCriteriaId"));
					String name = request.getParameter("subCriteriaName");
					
					dm.updateSubCriteria(id, name);
					
				}else if (action.equals("delSubCriteria")) {
					
					int id = Util.toInt(request.getParameter("subCriteriaId"));
					
					dm.delSubCriteria(id);
					
				}else if (action.equals("addProduct")){
					
					String products = request.getParameter("productList");
					String product = request.getParameter("product");
					
					int id = Util.toInt(request.getParameter("subCriteriaId"));
					
					if(products != null){
						String[] list = products.split("-");
						for (String string : list) {
							dm.addProductToSubCriteria(id, Util.toInt(string));
						}
					}else{
						dm.addProductToSubCriteria(id, Util.toInt(product));
					}
				}
			} catch (Exception e) {
				
				request.setAttribute("error", e.getMessage());
				// TODO: handle exception
			}
			
			request.getRequestDispatcher(url).forward(request, response);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}
